﻿using Core.FrameWork.Commons;
using Core.FrameWork.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.Web.Api.Utils.Init
{
    public static class InitJWTAuthentication
    {
        /// <summary>
        /// 使用JWT
        /// </summary>
        /// <param name="services"></param>
        public static void UseJWTAuthentication(this IServiceCollection services)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; ;

            }).AddJwtBearer(jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(APIConfig.JwtOption.Secret)),//秘钥
                    ValidateIssuer = true,
                    ValidIssuer = APIConfig.JwtOption.Issuer,
                    ValidateAudience = true,
                    ValidAudience = APIConfig.JwtOption.Audience,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.FromMinutes(5)
                };
            });
        }
    }
}
